<script lang="ts">
const reg = /\/assets\/svg\/(.+)\.svg/
const reg_get = /<svg[^>]*>([\s\S]*)<\/svg>/
const reg_width = /(<svg[^>]*)width="[^"]+"/
const reg_height = /(<svg[^>]*)height="[^"]+"/

const modules = new Map(
  Object.entries(
    import.meta.glob<string>('@/assets/svg/**/*.svg', { import: 'default', query: '?raw' })
  ).map(([key, value]) => [key.match(reg)![1], value])
)
</script>

<script lang="ts" setup>
const props = withDefaults(defineProps<{
  icon?: string,
  color?: string,
  size?: string
  formatter?: (svg: string) => string
}>(), {
  size: '1em'
})

const svg = ref('')
watchSyncEffect(async () => {
  const _icon = props.icon
  const formatter = props.formatter
  if (!_icon || !modules.has(_icon)) return
  let value = await modules.get(_icon)!()
  if (_icon !== props.icon) return
  value = value.match(reg_get)?.[0].replace(reg_width, '$1').replace(reg_height, '$1') || ''
  if (formatter) {
    value = formatter(value)
  }
  svg.value = value
})
</script>

<template>
  <div class="SvgIcon">
    <div v-html="svg" />
  </div>
</template>

<style lang="scss" scoped>
.SvgIcon {
  display: inline-block;
  width: v-bind('props.size');
  height: v-bind('props.size');
  color: v-bind('props.color');

  >div {
    height: 100%;
    padding: 1px;
    box-sizing: border-box;

    >* {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}
</style>
